package cn.e3mall.search.message;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.log4j.helpers.Loader;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import cn.e3mall.common.pojo.SearchItem;
import cn.e3mall.search.mapper.ItemMapper;

/**
 * 监听商品添加消息，接受消息后，将对应的商品信息同步到索引库里
 * @author zhouzhixiang
 *
 */
public class ItemAddMessageListner implements MessageListener {

	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private SolrServer solrserver;
	
	@Override
	public void onMessage(Message message) {
		
		try {
			//消息中取商品id
			TextMessage textMessage=(TextMessage) message;
			//根据商品id查询商品信息
			String text = textMessage.getText();
			Long itemId = new Long(text);
			//等待商品提交事务
			Thread.sleep(1000);
			//创建一个文档对象。并添加域
			SearchItem item = itemMapper.getItemById(itemId);
			SolrInputDocument document= new SolrInputDocument();
			document.addField("id", item.getId());
			document.addField("item_title", item.getTitle());
			document.addField("item_sell_point", item.getSell_point());
			document.addField("item_price", item.getPrice());
			document.addField("item_image", item.getImage());
			document.addField("item_category_name", item.getCategory_name());
			//把文档写入索引库
			solrserver.add(document);
			//提交
			solrserver.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
